﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain.BOM;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using MediatR;
using T.E.ERP.Write.API.Applicantions.Command.BOMCommand;
using Yitter.IdGenerator;

namespace T.E.ERP.Write.API.Applicantions.CommandHandler.BOMCommandHandler
{
    /// <summary>
    /// 修改Bom信息
    /// 物联网-智能MES生产管理系统-01-BOM管理V1.1-20250206
    /// </summary>
    public class UpdateBomCommandHandler : IRequestHandler<UpdateBomCommand, APIResult<int>>
    {
        /// <summary>
        /// BOM信息仓储
        /// </summary>
        private readonly IBaseRepository<BomInfo> bomRep;
        /// <summary>
        /// BOM配件仓储
        /// </summary>
        private readonly IBaseRepository<BomParts> partsRep;
        private readonly IBaseRepository<OperationRecord> operatRep;
        private readonly SDbContext db;

        public UpdateBomCommandHandler(IBaseRepository<BomInfo> bomRep, IBaseRepository<BomParts> partsRep, SDbContext db, IBaseRepository<OperationRecord> operatRep)
        {
            this.bomRep = bomRep;
            this.partsRep = partsRep;
            this.db = db;
            this.operatRep = operatRep;
        }
        public async Task<APIResult<int>> Handle(UpdateBomCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result=new APIResult<int>();
            using (var transaction = await db.Database.BeginTransactionAsync(cancellationToken))
            {
                try
                {

                    var bominfo = bomRep.GetAll().Result.Where(x => x.BomCode ==request.BomCode).FirstOrDefault();
                    bominfo.BomCode = request.BomCode;
                    bominfo.DefaultBom = request.DefaultBom;
                    bominfo.ProductType = request.ProductType;
                    bominfo.ProductName = request.ProductName;
                    bominfo.Remarks = request.Remarks;
                    bominfo.ProductionNum = request.ProductionNum;
                    bominfo.BomTheme = request.BomTheme;
                    bominfo.BomVersion = request.BomVersion;
                    bominfo.EstimatedCost = request.EstimatedCost;
                    bominfo.Inventory = request.Inventory;
                    bominfo.UpdateName=request.UpdateName;
                    bominfo.UpdateDate=DateTime.Now;
                    var set1 = await bomRep.Update(bominfo);
                    if (set1 > 0)
                    {
                        var res2 = partsRep.GetAll().Result.Where(x => x.BomCode== bominfo.BomCode).ToList();
                        foreach (var item in request.BomParts)
                        {
                            var i = 0;
                            res2[i].BomCode = item.BomCode;
                            res2[i].PartsCode = item.PartsCode;
                            res2[i].PartsName = item.PartsName;
                            res2[i].PartsType = item.PartsType;
                            res2[i].PartsUnit = item.PartsUnit;
                            res2[i].PartsBrand = item.PartsBrand;
                            res2[i].PartsNum = item.PartsNum;
                            res2[i].PartsLoss = item.PartsLoss;
                            res2[i].Inventory = item.Inventory;
                            res2[i].AvailableProduce = item.AvailableProduce;
                            res2[i].PId = item.PId;
                            var res3 = partsRep.Update(res2[i]).Result;
                            i += 1;
                        }
                        OperationRecord operation = new OperationRecord();
                        operation.OperationName = "张龙";
                        operation.OperationDate = DateTime.Now;
                        operation.OperationInfo = "修改";
                        int add4 = await operatRep.Add(operation);
                        //提交事务
                        await transaction.CommitAsync(cancellationToken);
                        result.Code = APIEnum.修改成功;
                        result.Msg = APIEnum.修改成功.ToString();
                        result.data = set1;
                    }
                    else
                    {
                        result.Code = APIEnum.修改失败;
                        result.Msg = APIEnum.修改失败.ToString();
                        //回滚事务
                        await transaction.RollbackAsync(cancellationToken);
                    }
                }
                catch (Exception ex)
                {
                    // 输出详细的错误信息
                    string errorMessage = $"添加失败: {ex.Message}";
                    if (ex.InnerException != null)
                    {
                        errorMessage += $" 内部异常: {ex.InnerException.Message}";
                    }
                    result.Code = APIEnum.添加失败;
                    result.Msg = errorMessage;
                    await transaction.RollbackAsync(cancellationToken);
                }
            }
            return result;
        }
    }
}
